package com.tzinfo.tzt.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tzinfo.data.TztData;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.util.SJKXAdapter;
import com.tzinfo.tzt.util.Car4SModeFragmentViewPagerAdapter;
import com.tzinfo.tzt.util.CirclePageIndicator;
import com.tzinfo.tzt.util.HttpUtils;
import com.tzinfo.tzt.util.Picdata;
import com.tzinfo.tzt.util.ResultMessage_NoData;
import com.tzinfo.tzt.util.ResultMessagee;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2014/11/9.
 */
public class Car4SModeActivity extends FragmentActivity {
    private TextView nameTv;
    private TextView addressTv;
    private TextView brandTv;
    private TextView tellTv;
    private TextView attentionTv;
    private TextView car4Smode_attention2;
    private LinearLayout group_ll;
    private ListView car4Smode_listView;
    private String id;
    private String image;

    private SJKXAdapter sjkxAdapter;
    double centerx;
    double centery;
    private ViewPager view_pager;
    private Car4SModeFragmentViewPagerAdapter adapter;
    private CirclePageIndicator circlePageIndicator;
    private LinearLayout gotomap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car4smode_1);

        Bundle extras = getIntent().getExtras();
        id = extras.getString("Id");
        image = extras.getString("image_url");
        centerx = extras.getDouble("centerx");
        centery = extras.getDouble("centery");


        nameTv = (TextView) findViewById(R.id.car4Smode_name);
        addressTv = (TextView) findViewById(R.id.car4Smode_address);
        brandTv = (TextView) findViewById(R.id.car4Smode_brand);
        tellTv = (TextView) findViewById(R.id.car4Smode_tell);
        gotomap = (LinearLayout) findViewById(R.id.car4Smode_gotomap);
        attentionTv = (TextView) findViewById(R.id.car4Smode_attention);
        car4Smode_attention2 = (TextView) findViewById(R.id.car4Smode_attention2);
        car4Smode_listView = (ListView) findViewById(R.id.car4Smode_listView);
        group_ll = (LinearLayout) findViewById(R.id.car4Smode_groupPurchase);
        group_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Car4SModeActivity.this, GroupPurchaseActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("Id", id);
                bundle.putString("image_url", image);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        GetData a = new GetData();
        a.execute();


        view_pager = (ViewPager) findViewById(R.id.car4Smode_viewpager);
        circlePageIndicator = (CirclePageIndicator) findViewById(R.id.car4Smode_CirclePageIndicator);


        attentionTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TztData.isUserLogin) {
                    new Attention().execute("0");
                }
             else {
                    Toast.makeText(Car4SModeActivity.this,"请先登录",Toast.LENGTH_SHORT).show();
                }
            }
        });
        car4Smode_attention2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Attention().execute("1");
            }
        });


    }

    public class GetData extends AsyncTask<String, Void, ResultMessagee> {

        @Override
        protected ResultMessagee doInBackground(String... params) {
            ResultMessagee result;
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("Id", id));
            pairs.add(new BasicNameValuePair("Sessionid", TztData.userInfo.getData().getSessionID()));//登陆用户的ID

            String GetDataUrl = "http://auto.tzinfo.net/mob/api/Car4SModel.ashx";
            String loginResultString = HttpUtils.doPostMethod(GetDataUrl, pairs);

            Gson gson = new Gson();
            result = gson.fromJson(loginResultString, ResultMessagee.class);
            return result;
        }

        @Override
        protected void onPostExecute(ResultMessagee result) {
            super.onPostExecute(result);
            if (result.getSuccess() == true) {
                if (result.getData().getIsA() > 0) {
                    attentionTv.setVisibility(View.GONE);
                    car4Smode_attention2.setVisibility(View.VISIBLE);
                } else if (result.getData().getIsA() == 0) {
                    attentionTv.setVisibility(View.VISIBLE);
                    car4Smode_attention2.setVisibility(View.GONE);
                }
                addressTv.setText(result.getData().getAddress());
                nameTv.setText(result.getData().getTitle());
                brandTv.setText(result.getData().getBrand());
                tellTv.setText(result.getData().getTell());

                //         List<String> image_url =  gson.fromJson(result.getData().getPic(), type);

                List<Picdata> picdatas = result.getData().getPic();
                adapter = new Car4SModeFragmentViewPagerAdapter(getSupportFragmentManager(), picdatas);
                view_pager.setAdapter(adapter);
                circlePageIndicator.setViewPager(view_pager);
                sjkxAdapter = new SJKXAdapter(Car4SModeActivity.this, result.getData().getNewList());
                //       adapter = new Car4SModeFragmentViewPagerAdapter(getSupportFragmentManager());
                car4Smode_listView.setAdapter(sjkxAdapter);
                setListViewHeightBasedOnChildren(car4Smode_listView);
                gotomap.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Uri location = Uri.parse("geo:" + centery + "," + centerx + "?q=" + nameTv.getText().toString());
                        Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);

// Verify it resolves
                        PackageManager packageManager = getPackageManager();
                        List<ResolveInfo> activities = packageManager.queryIntentActivities(mapIntent, 0);
                        boolean isIntentSafe = activities.size() > 0;

// Start an activity if it's safe
                        if (isIntentSafe) {
                            startActivity(mapIntent);
                        }
                    }
                });

            } else {
                Toast.makeText(Car4SModeActivity.this, result.getErrorMsg() + "搜寻失败", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    public class Attention extends AsyncTask<String, Void, ResultMessage_NoData> {

        @Override
        protected ResultMessage_NoData doInBackground(String... params) {
            ResultMessage_NoData result;
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("Sessionid", TztData.userInfo.getData().getSessionID()));//登陆用户的ID
            pairs.add(new BasicNameValuePair("cid", id));
            pairs.add(new BasicNameValuePair("Type", params[0]));//0:关注，1:取消关注

            String GetDataUrl = "http://auto.tzinfo.net/mob/api/Attention.ashx";
            String loginResultString = HttpUtils.doPostMethod(GetDataUrl, pairs);

            Gson gson = new Gson();
            result = gson.fromJson(loginResultString, ResultMessage_NoData.class);
            return result;
        }

        @Override
        protected void onPostExecute(ResultMessage_NoData result) {
            super.onPostExecute(result);
            Toast.makeText(Car4SModeActivity.this, result.getErrorMsg(), Toast.LENGTH_SHORT).show();
            if (attentionTv.getVisibility() == View.VISIBLE) {
                car4Smode_attention2.setVisibility(View.VISIBLE);
                attentionTv.setVisibility(View.GONE);
            } else {
                car4Smode_attention2.setVisibility(View.GONE);
                attentionTv.setVisibility(View.VISIBLE);
            }
        }
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    public void goBack(View v) {
        this.finish(); //关闭当前Activity
    }
}
